import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'

const Home = () => import('@/views/Home/index.vue')
const Student = () => import('@/views/Student/index.vue')
const Apartment = () => import('@/views/Apartment/index.vue')
const Dormitory = () => import('@/views/Dormitory/index.vue')
const Summary = () => import('@/views/Summary/index.vue')
const Login = () => import('@/views/Login/index.vue')
const notFound = () => import('@/views/notFound/index.vue')

const rightList = {
  'students': { path: 'students', name: 'students', component: Student },
  'apartments': { path: 'apartments', name: 'apartments', component: Apartment },
  'dormitorys': { path: 'dormitorys', name: 'dormitorys', component: Dormitory },
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    alias: '/home',
    redirect: '/summary',
    children: [
      {
        path: 'summary',
        name: 'summary',
        component: Summary,
        meta: { name: '概览' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/404',
    name: 'notFound',
    component: notFound
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export function initDynameicRoutes() {
  const menuList = store.getters.getMenuList
  // 动态添加二级路由
  menuList.forEach(item => {
    if(item.children.length) {
      item.children.forEach(it => {
        const route = rightList[it.path]
        route.meta = { name: it.authName }
        router.addRoute('home', route)
      })
    }
  })
}

// 不需要权限的路由
const whiteList = ['/login', '/404']
let registerRouteFresh = true
// 路由守卫
router.beforeEach((to, from, next) => {
  // 从 vuex 中获取 token
  const token = store.getters.getToken
  if(token) {
    if(to.path === '/login') {
      next('/')
    } else {
      // 如果首次或者刷新界面，next(...to, replace: true)会循环遍历路由，
      // 如果to找不到对应的路由那么他会再执行一次beforeEach((to, from, next))直到找到对应的路由，
      // 我们的问题在于页面刷新以后异步获取数据，直接执行next()感觉路由添加了但是在next()之后执行的，
      // 所以我们没法导航到相应的界面。这里使用变量registerRouteFresh变量做记录，直到找到相应的路由以后，
      // 把值设置为false然后走else执行next(),整个流程就走完了，路由也就添加完了。
      if (registerRouteFresh) {
        initDynameicRoutes()
        registerRouteFresh = false
        next(to.path)
      } else {
        // 第二次进来的时候判断是否有该路由，没有就跳404页面
        const roures = router.getRoutes()
        const bool = roures.find(item => item.path === to.path)
        if(bool) {
          next()
        } else {
          next('/404')
        }
      }
    }
  } else {
    if(whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router